﻿<!DOCTYPE html>
<html lang="en">

    <head>
        <title>File Sharing + Text Chat using WebRTC DataChannel</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
        <link rel="author" type="text/html" href="https://plus.google.com/+MuazKhan">
        <meta name="author" content="Muaz Khan">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        
        <link rel="stylesheet" href="https://cdn.webrtc-experiment.com/style.css">
        
        <style>
            td { vertical-align: top; }

            #chat-output div, #file-progress div {
                border: 1px solid black;
                border-bottom: 0;
                padding: .1em .4em;
            }

            input {
                border: 1px solid black;
                font-family: inherit;
                margin: .1em .3em;
                outline: none;
                padding: .1em .2em;
                width: 97%;
            }

            #chat-output, #file-progress {
                margin: 0 0 0 .4em;
                max-height: 12em;
                overflow: auto;
            }

            pre {
                border-left: 2px solid red;
                margin-left: 2em;
                padding-left: 1em;
            }
        </style>
        <!-- for HTML5 el styling -->
        <script>
            document.createElement('article');
            document.createElement('footer');
        </script>

        <script src="https://cdn.webrtc-experiment.com/DataChannel.js"> </script>
        <script src="https://cdn.webrtc-experiment.com/socket.io.js"> </script>
    </head>

    <body>
        <article>
            <h1>File Sharing + Text Chat using WebRTC <a
                                                          href="https://github.com/muaz-khan/WebRTC-Experiment/tree/master/DataChannel"
                                                          target="_blank">DataChannel</a>
            </h1>
            
            <div class="github-stargazers"></div>

                <p>
                    <a href="https://www.webrtc-experiment.com/">HOME</a>
                    <span> &copy; </span>
                    <a href="http://www.MuazKhan.com/" target="_blank">Muaz Khan</a>
                    
                    .
                    <a href="http://twitter.com/WebRTCWeb" target="_blank" title="Twitter profile for WebRTC Experiments">@WebRTCWeb</a>
                    
                    .
                    <a href="https://github.com/muaz-khan?tab=repositories" target="_blank" title="Github Profile">Github</a>
                    
                    .
                    <a href="https://github.com/muaz-khan/WebRTC-Experiment/issues?state=open" target="_blank">Latest issues</a>
                    
                    .
                    <a href="https://github.com/muaz-khan/WebRTC-Experiment/commits/master" target="_blank">What's New?</a>
                </p>
            
            <section>
                <h2>Open Data Channel</h2>
                <input type="text" id="channel" value="channel" style="font-size: 1.1em; text-align: right; width: 4em;"
                       title="channel name - use your own channel name">
                <button id="init-RTCMultiConnection">Open</button>
                <h2>or join:</h2>
                <button id="join-RTCMultiConnection">Join</button>
            </section>

            <table style="border-left: 1px solid black; width: 100%;">
                <tr>
                    <td>
                        <h2 style="display: block; font-size: 1em; text-align: center;">Text Chat</h2>

                        <div id="chat-output"></div>
                        <input type="text" id="chat-input" style="font-size: 1.2em;" placeholder="chat message" disabled>
                    </td>
                    <td style="background: white; border-left: 1px solid black;">
                        <h2 style="display: block; font-size: 1em; text-align: center;">Share Files</h2>
                        <input type="file" id="file" disabled>

                        <div id="file-progress"></div>
                    </td>
                </tr>
            </table>

            <script>
                document.getElementById('channel').value = Math.round(Math.random() * 60535) + 5000000;
            </script>

            <script>
                var channel = new DataChannel();

                // https://github.com/muaz-khan/WebRTC-Experiment/tree/master/socketio-over-nodejs
                var SIGNALING_SERVER = 'https://socketio-over-nodejs2.herokuapp.com:443/';
                channel.openSignalingChannel = function(config) {
                   var channel = config.channel || this.channel || 'default-namespace';
                   var sender = Math.round(Math.random() * 9999999999) + 9999999999;
                   
                   io.connect(SIGNALING_SERVER).emit('new-channel', {
                      channel: channel,
                      sender : sender
                   });
                   
                   var socket = io.connect(SIGNALING_SERVER + channel);
                   socket.channel = channel;
                   
                   socket.on('connect', function () {
                      if (config.callback) config.callback(socket);
                   });
                   
                   socket.send = function (message) {
                        socket.emit('message', {
                            sender: sender,
                            data  : message
                        });
                    };
                   
                   socket.on('message', config.onmessage);
                };

                channel.onmessage = function(data, userid, latency) {
                    console.debug(userid, 'posted', data);
                    appendDIV(data);
                    console.log('latency:', latency, 'ms');
                };

                channel.onopen = function() {
                    if (document.getElementById('chat-input')) document.getElementById('chat-input').disabled = false;
                    if (document.getElementById('file')) document.getElementById('file').disabled = false;

                    if (document.getElementById('init-RTCMultiConnection')) document.getElementById('init-RTCMultiConnection').disabled = true;
                };

                channel.onFileProgress = function(packets, uuid) {
                    appendDIV(uuid + ': ' + (
                            packets.sent
                                ? (packets.sent + ' sent')
                                : (packets.received + ' received')
                        ) + ' / ' + packets.remaining + ' remaining', 'file', fileProgress);
                };

                channel.onFileSent = function(file) {
                    appendDIV(file.name + ' sent.', fileProgress);
                };

                channel.onFileReceived = function(fileName) {
                    appendDIV(fileName + ' received.', fileProgress);
                };

                document.getElementById('init-RTCMultiConnection').onclick = function() {
                    channel.open(document.getElementById('channel').value || 'channel');
                    document.getElementById('join-RTCMultiConnection').disabled = true;
                    document.getElementById('init-RTCMultiConnection').disabled = true;
                };

                document.getElementById('join-RTCMultiConnection').onclick = function() {
                    channel.connect(document.getElementById('channel').value || 'channel');
                    document.getElementById('join-RTCMultiConnection').disabled = true;
                    document.getElementById('init-RTCMultiConnection').disabled = true;
                };

                document.getElementById('file').onchange = function() {
                    var file = this.files[0];
                    channel.send(file);
                };

                var chatOutput = document.getElementById('chat-output'),
                    fileProgress = document.getElementById('file-progress');

                function appendDIV(data, parent) {
                    var div = document.createElement('div');
                    div.innerHTML = data;

                    if (!parent) chatOutput.appendChild(div, chatOutput.firstChild);
                    else fileProgress.appendChild(div, fileProgress.firstChild);

                    div.tabIndex = 0;
                    div.focus();

                    chatInput.focus();
                }

                var chatInput = document.getElementById('chat-input');
                chatInput.onkeypress = function(e) {
                    if (e.keyCode !== 13 || !this.value) return;
                    appendDIV(this.value);
                    channel.send(this.value);
                    this.value = '';
                    this.focus();
                };

    /* users presence detection */
                channel.onleave = function(userid) {
                    var message = 'A user whose id is ' + userid + ' left you!';
                    appendDIV(message);
                    console.warn(message);
                };
            </script>
            <br/>
            <br/>

            <h2>Getting started with WebRTC <a href="https://github.com/muaz-khan/DataChannel"
                                               target="_blank">DataChannel</a></h2>
            <pre>
&lt;script src="https://cdn.webrtc-experiment.com/DataChannel.js"&gt;&lt;/script&gt;
&lt;script&gt;
    var channel = new <strong>DataChannel</strong>();

    // to create/open a new channel
    channel.<strong>open</strong>('channel-name');

    // to send text/data or file
    channel.<strong>send</strong>(file || data || 'text');
	
    // if soemone already created a channel; to join it: use "connect" method
    channel.<strong>connect</strong>('channel-name');
&lt;/script&gt;
</pre>
            Remember, A-to-Z, everything is optional! You can set <strong>channel-name</strong> in constructor or in
            <strong>open</strong>/<strong>connect</strong> methods. It is your choice!

            <br/>
            <br/>

            <h2>Features:</h2>
            <ol>
                <li>Send file directly &#8212; of any size</li>
                <li>Send text-message of any length</li>
                <li>Send data directly</li>
                <li>Simplest syntax ever! Same like WebSockets.</li>
                <li>Supports fallback to socket.io/websockets/etc.</li>
                <li>Auto users' presence detection</li>
                <li>Allows you eject any user; or close your entire data session</li>
            </ol>
            <br/>
            <br/>

            <h2>Additional:</h2>
            <pre>
&lt;script&gt;
    // to be alerted on data ports get open
    channel.<strong>onopen</strong> = function(userid) {}
	
    // to be alerted on data ports get new message
    channel.<strong>onmessage</strong> = function(message, userid) {}
	
    // by default; connection is [many-to-many]; you can use following directions
    channel.<strong>direction</strong> = 'one-to-one';
    channel.<strong>direction</strong> = 'one-to-many';
    channel.<strong>direction</strong> = 'many-to-many';	// --- it is default

    // show progress bar!
    channel.<strong>onFileProgress</strong> = function (packets) {
        // packets.remaining
        // packets.sent
        // packets.received
        // packets.length
    };

    // on file successfully sent
    channel.<strong>onFileSent</strong> = function (file) {
        // file.name
        // file.size
    };

    // on file successfully received
    channel.<strong>onFileReceived</strong> = function (fileName) {};
&lt;/script&gt;
</pre>
            <br/>
            <br/>

            <h2>Errors Handling</h2>
            <pre>
&lt;script&gt;
    // error to open data ports
    channel.<strong>onerror</strong> = function(event) {}
	
    // data ports suddenly dropped
    channel.<strong>onclose</strong> = function(event) {}
&lt;/script&gt;
</pre>
            <br/>
            <br/>

            <h2>Use your own socket.io for signaling</h2>
            <pre>
&lt;script&gt;
    // by default socket.io is used for signaling; you can override it
    channel.<strong>openSignalingChannel</strong> = function(config) {
        var socket = io.connect('http://your-site:8888');
        socket.channel = config.channel || this.channel || 'default-channel';
        socket.on('message', config.onmessage);

        socket.send = function (data) {
            socket.emit('message', data);
        };

        if (config.onopen) setTimeout(config.onopen, 1);
        return socket;
    }
&lt;/script&gt;
</pre>
            <br/>
            <br/>
            <section style="border: 1px solid rgb(189, 189, 189); border-radius: .2em; margin: 1em 3em;">
                <h2 id="feedback" style="border-bottom: 1px solid rgb(189, 189, 189); padding: .2em .4em;">Feedback</h2>

                <div>
                    <textarea id="message"
                              style="border: 1px solid rgb(189, 189, 189); height: 8em; margin: .2em; outline: none; resize: vertical; width: 98%;"
                              placeholder="Have any message? Suggestions or something went wrong?"></textarea>
                </div>
                <button id="send-message" style="font-size: 1em;">Send Message</button>
            </section>
            
            <section class="experiment own-widgets latest-commits">
                <h2 class="header" id="updates" style="color: red; padding-bottom: .1em;"><a href="https://github.com/muaz-khan/WebRTC-Experiment/commits/master" target="_blank">Latest Updates</a></h2>
                <div id="github-commits"></div>
            </section>
        </article>
        
        <a href="https://github.com/muaz-khan/DataChannel" class="fork-left"></a>
        
        <footer>
            <p>
                <a href="https://www.webrtc-experiment.com/">WebRTC Experiments</a>
                © <a href="https://plus.google.com/+MuazKhan" rel="author" target="_blank">Muaz Khan</a>
                <a href="mailto:muazkh@gmail.com" target="_blank">muazkh@gmail.com</a>
            </p>
        </footer>
        
        <script src="https://cdn.webrtc-experiment.com/commits.js" async> </script>
    </body>
</html>
